<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>订单管理 - 电信套餐订购系统</title>
    <!-- 引入项目现有的CSS -->
    <link rel="stylesheet" href="./css/github-markdown-light.css">
    <style>
        body {
            margin: 0;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif;
            background-color: #f6f8fa;
            color: #1f2328;
            min-height: 100vh;
        }
        
        .container {
            width: 100%;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            box-sizing: border-box;
        }
        
        .header {
            background-color: #ffffff;
            padding: 20px;
            border: 1px solid #d1d9e0;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .header h1 {
            margin: 0;
            font-size: 24px;
            color: #1f2328;
        }
        
        .btn-group {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            text-decoration: none;
            transition: all 0.2s ease;
        }
        
        .btn-primary {
            background-color: #0969da;
            color: #ffffff;
        }
        
        .btn-primary:hover {
            background-color: #085aa8;
        }
        
        .btn-secondary {
            background-color: #f6f8fa;
            color: #1f2328;
            border: 1px solid #d1d9e0;
        }
        
        .btn-secondary:hover {
            background-color: #e1e4e8;
        }
        
        .logout-btn {
            padding: 8px 16px;
            background-color: #d73a49;
            color: #ffffff;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            text-decoration: none;
        }
        
        .logout-btn:hover {
            background-color: #cb2431;
        }
        
        .search-section {
            background-color: #ffffff;
            padding: 20px;
            border: 1px solid #d1d9e0;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .search-form {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            align-items: end;
        }
        
        .form-group {
            display: flex;
            flex-direction: column;
        }
        
        .form-label {
            margin-bottom: 5px;
            font-size: 14px;
            font-weight: 500;
            color: #1f2328;
        }
        
        .form-input,
        .form-select {
            padding: 8px 12px;
            border: 1px solid #d1d9e0;
            border-radius: 6px;
            font-size: 14px;
            transition: border-color 0.2s ease;
        }
        
        .form-input:focus,
        .form-select:focus {
            outline: none;
            border-color: #0969da;
            box-shadow: 0 0 0 3px rgba(9, 105, 218, 0.1);
        }
        
        .status-badge {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: 500;
        }
        
        .status-pending {
            background-color: #ffeaa7;
            color: #856404;
        }
        
        .status-paid {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-active {
            background-color: #cce7ff;
            color: #004085;
        }
        
        .status-canceled {
            background-color: #f8d7da;
            color: #721c24;
        }
        
        .orders-table {
            width: 100%;
            border-collapse: collapse;
            background-color: #ffffff;
            border: 1px solid #d1d9e0;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        
        .orders-table th,
        .orders-table td {
            padding: 12px 16px;
            text-align: left;
            border-bottom: 1px solid #d1d9e0;
        }
        
        .orders-table th {
            background-color: #f6f8fa;
            font-weight: 600;
            color: #1f2328;
            white-space: nowrap;
        }
        
        .orders-table tbody tr:hover {
            background-color: #f6f8fa;
        }
        
        .orders-table tbody tr:last-child td {
            border-bottom: none;
        }
        
        .pagination {
            display: flex;
            justify-content: center;
            align-items: center;
            margin-top: 20px;
            gap: 5px;
        }
        
        .pagination-btn {
            padding: 6px 12px;
            border: 1px solid #d1d9e0;
            background-color: #ffffff;
            color: #1f2328;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            transition: all 0.2s ease;
        }
        
        .pagination-btn:hover {
            background-color: #f6f8fa;
        }
        
        .pagination-btn.active {
            background-color: #0969da;
            color: #ffffff;
            border-color: #0969da;
        }
        
        .pagination-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #818b98;
        }
        
        .empty-state i {
            font-size: 48px;
            margin-bottom: 16px;
            display: block;
        }
        
        /* 订单详情模态框 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
        }
        
        .modal-content {
            background-color: #ffffff;
            margin: 10% auto;
            padding: 20px;
            border: 1px solid #d1d9e0;
            border-radius: 8px;
            width: 90%;
            max-width: 800px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 15px;
            border-bottom: 1px solid #d1d9e0;
        }
        
        .modal-header h2 {
            margin: 0;
            font-size: 20px;
            color: #1f2328;
        }
        
        .modal-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #818b98;
            padding: 0;
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 6px;
        }
        
        .modal-close:hover {
            background-color: #f6f8fa;
            color: #1f2328;
        }
        
        .order-details {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
        }
        
        .detail-section {
            padding: 15px;
            border: 1px solid #d1d9e0;
            border-radius: 6px;
            background-color: #f6f8fa;
        }
        
        .detail-section h3 {
            margin: 0 0 15px 0;
            font-size: 16px;
            color: #1f2328;
        }
        
        .detail-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
            font-size: 14px;
        }
        
        .detail-label {
            color: #818b98;
        }
        
        .detail-value {
            color: #1f2328;
            font-weight: 500;
        }
        
        .action-buttons {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="search-section">
            <h2 style="margin-top: 0; margin-bottom: 20px;font-size: 1.2em;">订单查询</h2>
            <form id="searchForm" class="search-form">
                <div class="form-group">
                    <label class="form-label" for="orderId">订单编号</label>
                    <input type="text" id="orderId" class="form-input" placeholder="请输入订单编号">
                </div>
                <div class="form-group">
                    <label class="form-label" for="userId">用户ID</label>
                    <input type="text" id="userId" class="form-input" placeholder="请输入用户ID">
                </div>
                <div class="form-group">
                    <label class="form-label" for="status">订单状态</label>
                    <select id="status" class="form-select">
                        <option value="">全部状态</option>
                        <option value="pending">待支付</option>
                        <option value="paid">已支付</option>
                        <option value="active">已生效</option>
                        <option value="canceled">已取消</option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="form-label" for="startDate">开始日期</label>
                    <input type="date" id="startDate" class="form-input">
                </div>
                <div class="form-group">
                    <label class="form-label" for="endDate">结束日期</label>
                    <input type="date" id="endDate" class="form-input">
                </div>
                <div class="form-group" style="display: flex; gap: 10px;">
                    <button type="submit" class="btn btn-primary" style="flex: 1;">查询</button>
                    <button type="button" id="resetBtn" class="btn btn-secondary" style="flex: 1;">重置</button>
                </div>
            </form>
        </div>
        
        <div style="overflow-x: auto;">
            <table class="orders-table">
                <thead>
                    <tr style="font-size: 0.8em;">
                        <th>订单编号</th>
                        <th>用户ID</th>
                        <th>用户名称</th>
                        <th>套餐ID</th>
                        <th>套餐名称</th>
                        <th>订单金额</th>
                        <th>优惠金额</th>
                        <th>实付金额</th>
                        <th>订单状态</th>
                        <th>创建时间</th>
                        <th>支付时间</th>
                        <th>生效时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="ordersTableBody">
                    <!-- 订单数据将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
        
        <div class="pagination">
            <button class="pagination-btn" id="prevPage" disabled>上一页</button>
            <span id="pageNumbers"></span>
            <button class="pagination-btn" id="nextPage">下一页</button>
        </div>
    </div>
    
    <!-- 订单详情模态框 -->
    <div id="orderDetailModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>订单详情</h2>
                <button class="modal-close">&times;</button>
            </div>
            <div id="orderDetailContent" class="order-details">
                <!-- 订单详情内容将通过JavaScript动态填充 -->
            </div>
        </div>
    </div>
    
    <script>
        // 环境切换开关：'dev' 开发环境（调用本地http接口），'prod' 生产环境（调用/api接口）
        const ENV_MODE = 'prod'; // 修改此值切换环境
        
        // 全局变量
        let orders = []; // 订单数据
        let filteredOrders = []; // 筛选后的订单数据
        let currentPage = 1;
        const pageSize = 10;
        
        // DOM元素
        const ordersTableBody = document.getElementById('ordersTableBody');
        const searchForm = document.getElementById('searchForm');
        const resetBtn = document.getElementById('resetBtn');
        const prevPageBtn = document.getElementById('prevPage');
        const nextPageBtn = document.getElementById('nextPage');
        const pageNumbers = document.getElementById('pageNumbers');
        const orderDetailModal = document.getElementById('orderDetailModal');
        const modalCloseBtn = document.querySelector('.modal-close');
        const orderDetailContent = document.getElementById('orderDetailContent');
        
        // 从接口获取用户数据
        async function fetchUsers() {
            try {
                const apiUrl = ENV_MODE === 'dev' 
                    ? 'http://localhost:8181/ai/taocan/listUser' 
                    : '/api/taocan/listUser';
                
                const response = await fetch(apiUrl);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                // 接口直接返回List<UserCommProfile>，无需从users字段提取
                const data = await response.json();
                // 确保返回的是数组，并转换为我们需要的格式
                return Array.isArray(data) ? 
                    data.map(user => ({
                        userId: `USER${String(user.id || user.userId).padStart(3, '0')}`,
                        userName: user.userName
                    })) : 
                    [];
            } catch (error) {
                console.error('获取用户数据失败:', error);
                // 返回模拟用户数据作为备用
                return generateMockUsers();
            }
        }
        
        // 从接口获取套餐数据
        async function fetchPackages() {
            try {
                const apiUrl = ENV_MODE === 'dev' 
                    ? 'http://localhost:8181/ai/taocan/listTaocan' 
                    : '/api/taocan/listTaocan';
                
                const response = await fetch(apiUrl);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                // 接口直接返回List<PackageInfoVO>，无需从packages字段提取
                const data = await response.json();
                // 确保返回的是数组，并转换为我们需要的格式
                return Array.isArray(data) ? 
                    data.map(pkg => ({
                        id: pkg.id || pkg.packageId,
                        name: pkg.name
                    })) : 
                    [];
            } catch (error) {
                console.error('获取套餐数据失败:', error);
                // 返回模拟套餐数据作为备用
                return generateMockPackages();
            }
        }
        
        // 生成模拟用户数据（备用）
        function generateMockUsers() {
            const mockUsers = [];
            for (let i = 1; i <= 30; i++) {
                mockUsers.push({
                    userId: `USER${String(i).padStart(3, '0')}`,
                    userName: `用户${i}`
                });
            }
            return mockUsers;
        }
        
        // 生成模拟套餐数据（备用）
        function generateMockPackages() {
            return [
                { id: '1', name: '基础套餐' },
                { id: '2', name: '流量王套餐' },
                { id: '3', name: '通话无忧套餐' },
                { id: '4', name: '商务精英套餐' },
                { id: '5', name: '家庭共享套餐' },
                { id: '6', name: '学生特惠套餐' },
                { id: '7', name: '老年关爱套餐' }
            ];
        }
        
        // 使用API数据生成订单
        function generateOrdersFromApiData(users, packages) {
            const statuses = ['pending', 'paid', 'active', 'canceled'];
            const statusNames = {
                'pending': '待支付',
                'paid': '已支付',
                'active': '已生效',
                'canceled': '已取消'
            };
            
            const orders = [];
            // 生成30-50个订单
            const orderCount = 30 + Math.floor(Math.random() * 21);
            
            for (let i = 1; i <= orderCount; i++) {
                const randomDate = new Date();
                randomDate.setDate(randomDate.getDate() - Math.floor(Math.random() * 30));
                
                const status = statuses[Math.floor(Math.random() * statuses.length)];
                const selectedUser = users[Math.floor(Math.random() * users.length)];
                const selectedPackage = packages[Math.floor(Math.random() * packages.length)];
                const originalPrice = Math.floor(Math.random() * 100) + 50;
                const discountAmount = Math.floor(Math.random() * originalPrice / 2);
                const actualPrice = originalPrice - discountAmount;
                
                let paymentDate = null;
                let effectiveDate = null;
                
                if (status === 'paid') {
                    paymentDate = new Date(randomDate);
                    paymentDate.setHours(paymentDate.getHours() + Math.floor(Math.random() * 24));
                } else if (status === 'active') {
                    paymentDate = new Date(randomDate);
                    paymentDate.setHours(paymentDate.getHours() + Math.floor(Math.random() * 24));
                    effectiveDate = new Date(paymentDate);
                    effectiveDate.setDate(effectiveDate.getDate() + Math.floor(Math.random() * 7));
                }
                
                orders.push({
                    id: `ORD${String(i).padStart(6, '0')}`,
                    userId: selectedUser.userId,
                    userName: selectedUser.userName,
                    packageId: selectedPackage.id,
                    packageName: selectedPackage.name,
                    originalPrice: originalPrice,
                    discountAmount: discountAmount,
                    actualPrice: actualPrice,
                    status: status,
                    statusName: statusNames[status],
                    createTime: randomDate,
                    paymentTime: paymentDate,
                    effectiveTime: effectiveDate
                });
            }
            
            // 按创建时间降序排序
            return orders.sort((a, b) => b.createTime - a.createTime);
        }
        
        // 生成完全模拟的订单数据（接口全部失败时使用）
        function generateMockOrders() {
            const users = generateMockUsers();
            const packages = generateMockPackages();
            return generateOrdersFromApiData(users, packages);
        }
        
        // 格式化日期
        function formatDate(date) {
            if (!date) return '-';
            const d = new Date(date);
            const year = d.getFullYear();
            const month = String(d.getMonth() + 1).padStart(2, '0');
            const day = String(d.getDate()).padStart(2, '0');
            const hours = String(d.getHours()).padStart(2, '0');
            const minutes = String(d.getMinutes()).padStart(2, '0');
            const seconds = String(d.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
        
        // 获取状态对应的样式类
        function getStatusClass(status) {
            switch (status) {
                case 'pending': return 'status-pending';
                case 'paid': return 'status-paid';
                case 'active': return 'status-active';
                case 'canceled': return 'status-canceled';
                default: return '';
            }
        }
        
        // 渲染订单列表
        function renderOrders() {
            ordersTableBody.innerHTML = '';
            
            const startIndex = (currentPage - 1) * pageSize;
            const endIndex = startIndex + pageSize;
            const currentOrders = filteredOrders.slice(startIndex, endIndex);
            
            if (currentOrders.length === 0) {
                const emptyRow = document.createElement('tr');
                emptyRow.innerHTML = `
                    <td colspan="13" class="empty-state">
                        <i>📋</i>
                        <p>暂无订单数据</p>
                    </td>
                `;
                ordersTableBody.appendChild(emptyRow);
                return;
            }
            
            currentOrders.forEach(order => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${order.id}</td>
                    <td>${order.userId}</td>
                    <td>${order.userName}</td>
                    <td>${order.packageId}</td>
                    <td>${order.packageName}</td>
                    <td>¥${order.originalPrice.toFixed(2)}</td>
                    <td>¥${order.discountAmount.toFixed(2)}</td>
                    <td>¥${order.actualPrice.toFixed(2)}</td>
                    <td><span class="status-badge ${getStatusClass(order.status)}">${order.statusName}</span></td>
                    <td>${formatDate(order.createTime)}</td>
                    <td>${formatDate(order.paymentTime)}</td>
                    <td>${formatDate(order.effectiveTime)}</td>
                    <td>
                        <button class="btn btn-secondary" onclick="viewOrderDetail('${order.id}')" style="padding: 4px 8px; font-size: 12px;">查看详情</button>
                    </td>
                `;
                ordersTableBody.appendChild(row);
            });
        }
        
        // 渲染分页
        function renderPagination() {
            const totalPages = Math.ceil(filteredOrders.length / pageSize);
            
            // 禁用/启用上一页和下一页按钮
            prevPageBtn.disabled = currentPage === 1;
            nextPageBtn.disabled = currentPage === totalPages || totalPages === 0;
            
            // 渲染页码
            pageNumbers.innerHTML = '';
            
            const maxVisiblePages = 5;
            let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
            let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
            
            if (endPage - startPage + 1 < maxVisiblePages) {
                startPage = Math.max(1, endPage - maxVisiblePages + 1);
            }
            
            // 第一页按钮
            if (startPage > 1) {
                const firstPageBtn = document.createElement('button');
                firstPageBtn.className = 'pagination-btn';
                firstPageBtn.textContent = '1';
                firstPageBtn.addEventListener('click', () => { currentPage = 1; updateOrdersDisplay(); });
                pageNumbers.appendChild(firstPageBtn);
                
                if (startPage > 2) {
                    const ellipsis = document.createTextNode('...');
                    pageNumbers.appendChild(ellipsis);
                }
            }
            
            // 中间页码按钮
            for (let i = startPage; i <= endPage; i++) {
                const pageBtn = document.createElement('button');
                pageBtn.className = `pagination-btn ${i === currentPage ? 'active' : ''}`;
                pageBtn.textContent = i;
                pageBtn.addEventListener('click', () => { currentPage = i; updateOrdersDisplay(); });
                pageNumbers.appendChild(pageBtn);
            }
            
            // 最后一页按钮
            if (endPage < totalPages) {
                if (endPage < totalPages - 1) {
                    const ellipsis = document.createTextNode('...');
                    pageNumbers.appendChild(ellipsis);
                }
                
                const lastPageBtn = document.createElement('button');
                lastPageBtn.className = 'pagination-btn';
                lastPageBtn.textContent = totalPages;
                lastPageBtn.addEventListener('click', () => { currentPage = totalPages; updateOrdersDisplay(); });
                pageNumbers.appendChild(lastPageBtn);
            }
        }
        
        // 更新订单显示
        function updateOrdersDisplay() {
            renderOrders();
            renderPagination();
        }
        
        // 查看订单详情
        function viewOrderDetail(orderId) {
            const order = filteredOrders.find(o => o.id === orderId);
            if (!order) return;
            
            orderDetailContent.innerHTML = `
                <div class="detail-section">
                    <h3>订单信息</h3>
                    <div class="detail-item">
                        <span class="detail-label">订单编号</span>
                        <span class="detail-value">${order.id}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">订单状态</span>
                        <span class="detail-value"><span class="status-badge ${getStatusClass(order.status)}">${order.statusName}</span></span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">创建时间</span>
                        <span class="detail-value">${formatDate(order.createTime)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">支付时间</span>
                        <span class="detail-value">${formatDate(order.paymentTime)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">生效时间</span>
                        <span class="detail-value">${formatDate(order.effectiveTime)}</span>
                    </div>
                </div>
                
                <div class="detail-section">
                    <h3>用户信息</h3>
                    <div class="detail-item">
                        <span class="detail-label">用户ID</span>
                        <span class="detail-value">${order.userId}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">用户名称</span>
                        <span class="detail-value">${order.userName}</span>
                    </div>
                </div>
                
                <div class="detail-section">
                    <h3>套餐信息</h3>
                    <div class="detail-item">
                        <span class="detail-label">套餐ID</span>
                        <span class="detail-value">${order.packageId}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">套餐名称</span>
                        <span class="detail-value">${order.packageName}</span>
                    </div>
                </div>
                
                <div class="detail-section">
                    <h3>金额信息</h3>
                    <div class="detail-item">
                        <span class="detail-label">套餐原价</span>
                        <span class="detail-value">¥${order.originalPrice.toFixed(2)}</span>
                    </div>
                    <div class="detail-item">
                        <span class="detail-label">优惠金额</span>
                        <span class="detail-value">¥${order.discountAmount.toFixed(2)}</span>
                    </div>
                    <div class="detail-item" style="font-weight: bold;">
                        <span class="detail-label">实付金额</span>
                        <span class="detail-value">¥${order.actualPrice.toFixed(2)}</span>
                    </div>
                </div>
            `;
            
            // 显示模态框
            orderDetailModal.style.display = 'block';
        }
        
        // 关闭订单详情模态框
        function closeOrderDetailModal() {
            orderDetailModal.style.display = 'none';
        }
        
        // 筛选订单
        function filterOrders() {
            const orderId = document.getElementById('orderId').value.toLowerCase().trim();
            const userId = document.getElementById('userId').value.toLowerCase().trim();
            const status = document.getElementById('status').value;
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;
            
            filteredOrders = orders.filter(order => {
                // 订单编号筛选
                if (orderId && !order.id.toLowerCase().includes(orderId)) {
                    return false;
                }
                
                // 用户ID筛选
                if (userId && !order.userId.toLowerCase().includes(userId)) {
                    return false;
                }
                
                // 订单状态筛选
                if (status && order.status !== status) {
                    return false;
                }
                
                // 日期范围筛选
                const orderDate = new Date(order.createTime).toISOString().split('T')[0];
                if (startDate && orderDate < startDate) {
                    return false;
                }
                if (endDate && orderDate > endDate) {
                    return false;
                }
                
                return true;
            });
            
            // 重置到第一页
            currentPage = 1;
            
            // 更新显示
            updateOrdersDisplay();
        }
        
        // 重置搜索表单
        function resetSearchForm() {
            document.getElementById('orderId').value = '';
            document.getElementById('userId').value = '';
            document.getElementById('status').value = '';
            document.getElementById('startDate').value = '';
            document.getElementById('endDate').value = '';
        }
        
        // 从接口获取订单数据
        async function fetchOrders() {
            try {
                const apiUrl = ENV_MODE === 'dev' 
                    ? 'http://localhost:8181/ai/taocan/order/list' 
                    : '/api/taocan/order/list';
                
                const response = await fetch(apiUrl);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const data = await response.json();
                console.log('API响应数据:', data);
                
                // 检查是否是Result格式的响应
                if (data.code === 200 ) {
                    if (Array.isArray(data.data)) {
                        console.log('成功获取到订单数据，数量:', data.data.length);
                        // 处理从接口返回的订单数据，确保字段格式正确
                        const processedOrders = data.data.map(order => ({
                            id: order.id || order.orderId || '',
                            userId: order.userId || '',
                            userName: order.userName || '',
                            packageId: order.packageId || '',
                            packageName: order.packageName || '',
                            originalPrice: parseFloat(order.originalPrice || order.totalPrice || 0),
                            discountAmount: parseFloat(order.discountAmount || 0),
                            actualPrice: parseFloat(order.actualPrice || order.paidPrice || 0),
                            status: order.status || 'pending',
                            statusName: order.statusName || getStatusName(order.status),
                            createTime: order.createTime ? new Date(order.createTime) : null,
                            paymentTime: order.paymentTime ? new Date(order.paymentTime) : null,
                            effectiveTime: order.effectiveTime ? new Date(order.effectiveTime) : null
                        }));
                        console.log('处理后的订单数据:', processedOrders);
                        return processedOrders;
                    } else {
                        console.warn('API返回失败或数据为空:', data);
                        return [];
                    }
                } else if (Array.isArray(data)) {
                    // 如果直接返回数组，也进行处理
                    console.log('API直接返回数组数据，数量:', data.length);
                    return data.map(order => ({
                        id: order.id || order.orderId || '',
                        userId: order.userId || '',
                        userName: order.userName || '',
                        packageId: order.packageId || '',
                        packageName: order.packageName || '',
                        originalPrice: parseFloat(order.originalPrice || order.totalPrice || 0),
                        discountAmount: parseFloat(order.discountAmount || 0),
                        actualPrice: parseFloat(order.actualPrice || order.paidPrice || 0),
                        status: order.status || 'pending',
                        statusName: order.statusName || getStatusName(order.status),
                        createTime: order.createTime ? new Date(order.createTime) : null,
                        paymentTime: order.paymentTime ? new Date(order.paymentTime) : null,
                        effectiveTime: order.effectiveTime ? new Date(order.effectiveTime) : null
                    }));
                } else {
                    console.error('无效的响应格式:', data);
                    throw new Error('Invalid response format');
                }
            } catch (error) {
                console.error('获取订单数据失败:', error);
                // 返回空数组，让上层处理
                return [];
            }
        }
        
        // 根据状态获取状态名称
        function getStatusName(status) {
            const statusNames = {
                'pending': '待支付',
                'paid': '已支付',
                'active': '已生效',
                'canceled': '已取消'
            };
            return statusNames[status] || status;
        }
        
        // 初始化订单数据
        async function initializeOrders() {
            try {
                // 显示加载状态
                ordersTableBody.innerHTML = `
                    <tr>
                        <td colspan="13" class="empty-state">
                            <i>⏳</i>
                            <p>正在加载订单数据...</p>
                        </td>
                    </tr>
                `;
                
                // 从API获取订单数据
                console.log('开始从API获取订单数据');
                orders = await fetchOrders();
                console.log('fetchOrders返回的订单数据:', orders);
                console.log('订单数据长度:', orders ? orders.length : 'undefined');
                
                // 如果没有获取到订单数据，使用模拟数据
                if (!orders || orders.length === 0) {
                    console.warn('未获取到订单数据，使用模拟数据');
                    const [users, packages] = await Promise.all([
                        fetchUsers(),
                        fetchPackages()
                    ]);
                    orders = generateOrdersFromApiData(users, packages);
                    console.log('生成的模拟订单数据数量:', orders.length);
                }
                
                filteredOrders = [...orders];
            } catch (error) {
                console.error('初始化订单数据失败:', error);
                // 接口失败时使用完全模拟数据
                orders = generateMockOrders();
                filteredOrders = [...orders];
            } finally {
                // 更新显示
                updateOrdersDisplay();
            }
        }
        
        // 事件监听
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化订单数据
            initializeOrders();
            
            // 搜索表单提交
            searchForm.addEventListener('submit', function(e) {
                e.preventDefault();
                filterOrders();
            });
            
            // 重置按钮点击
            resetBtn.addEventListener('click', function() {
                resetSearchForm();
                filteredOrders = [...orders];
                currentPage = 1;
                updateOrdersDisplay();
            });
            
            // 分页按钮点击
            prevPageBtn.addEventListener('click', function() {
                if (currentPage > 1) {
                    currentPage--;
                    updateOrdersDisplay();
                }
            });
            
            nextPageBtn.addEventListener('click', function() {
                const totalPages = Math.ceil(filteredOrders.length / pageSize);
                if (currentPage < totalPages) {
                    currentPage++;
                    updateOrdersDisplay();
                }
            });
            
            // 关闭模态框
            modalCloseBtn.addEventListener('click', closeOrderDetailModal);
            
            // 点击模态框外部关闭
            window.addEventListener('click', function(event) {
                if (event.target === orderDetailModal) {
                    closeOrderDetailModal();
                }
            });
        });
        
        // 暴露viewOrderDetail函数到全局
        window.viewOrderDetail = viewOrderDetail;
    </script>
</body>
</html>